// pages/my-message/my-message.js
const app = getApp();
const db = wx.cloud.database().collection("user");

Page({
  data: {
    dialogKey: '',
    showWithName: false,
    showWithSex: false,
    showWithPhone: false,
    showWithWechat: false,
    showTextAndTitleWithInput: false,
    userInfo: {}, // 用户信息对象，包含头像和姓名
    identity:'',
    oldAvatarUrl:'',
    tempFilePath:'',
    newName:''
    
  },
  refreshPageContent() {
    db.get().then(res => {
      if (res.data && res.data.length > 0) {
        const userInfo = res.data[0];
        let identity = '';
        if(userInfo.identity === 0) {
          identity = '游客';
        } else if(userInfo.identity === 1) {
          identity = '用户';
        } else if(userInfo.identity === 2) {
          identity = '公司';
        }
        this.setData({ userInfo, identity });
      }
    }).catch(err => {
      console.error('查询用户信息失败：', err);
    });
  },
  onLoad: function (options) {
    this.refreshPageContent();
  },
  

  showDialog(e) {
    const { key } = e.currentTarget.dataset;
    this.setData({ [key]: true, dialogKey: key });
  },

  closeDialog() {
    const { dialogKey } = this.data;
    this.setData({ [dialogKey]: false });
  },
  onChooseAvatar(e) {
    console.log(e.detail)
    const {  avatarUrl } = e.detail; // 获取用户选择的临时文件路径
    console.log( avatarUrl)
    const oldAvatarUrl = this.data.userInfo.avatarUrl; // 获取当前用户头像地址

    // 上传新头像到云存储
    wx.cloud.uploadFile({
      cloudPath: 'user/avatar/' + new Date().getTime() + '.png', // 云存储中的路径及文件名
      filePath:  avatarUrl, // 本地临时文件路径
      success: res => {
        // 获取上传成功后的文件 ID
        const newAvatarUrl = res.fileID;

        // 更新数据库中的用户头像信息
        wx.cloud.database().collection('user').where({
          _openid: this.data.userInfo._openid // 使用用户的 openid 来查询
        }).update({
          data: {
            avatarUrl: newAvatarUrl
          },
          success: () => {
            console.log('用户头像更新成功');

            // 删除之前的头像文件
            wx.cloud.deleteFile({
              fileList: [oldAvatarUrl],
              success: res => {
                console.log('原头像文件删除成功');
              },
              fail: err => {
                console.error('原头像文件删除失败', err);
              }
            });

            // 更新页面数据
            this.setData({
              "userInfo.avatarUrl": newAvatarUrl
            });
          },
          fail: err => {
            console.error('用户头像更新失败', err);
          }
        });
      },
      fail: err => {
        console.error('头像上传失败', err);
      }
    });
  },
  onUnload: function () {
    const pages = getCurrentPages(); // 获取当前页面栈
    const prevPage = pages[pages.length - 2]; // 获取上个页面
    if (prevPage) {
      // 如果上个页面存在，就调用上个页面的 setData() 方法设置需要刷新的数据
      prevPage.setData({
        needRefresh: true
      });
    }
    // 返回上个页面
    wx.navigateBack({
      delta: 1
    });
  },
  onInputName(event) {
    const newName = event.detail.value;
    console.log('New Name:', newName);
    this.setData({
      'userInfo.nickName': newName
    });
  },
  
  confirmName() {
    wx.cloud.database().collection('user').where({
      _openid: this.data.userInfo._openid 
    }).update({
      data: {
        nickName: this.data.userInfo.nickName
      },
      success: () => {
        console.log('姓名更新成功');
        this.closeDialog();
        this.refreshPageContent();
      },
      fail: err => {
        console.error('姓名更新失败', err);
      }
    });
  },
  onInputSex(event) {
    const newSex = event.detail.value;
    console.log('New Sex:', newSex);
  
    if (newSex !== '男' && newSex !== '女') {
      wx.showToast({
        title: '性别只能输入“男”或“女”',
        icon: 'none'
      });
      return; 
    }
  

    this.setData({
      'userInfo.sex': newSex
    });
  },
  
  
  onInputPhone(event) {
    const newPhone = event.detail.value;
    console.log('New Phone:', newPhone);
    this.setData({
      'userInfo.phone': newPhone
    });
  },
  
  onInputWechat(event) {
    const newWechat = event.detail.value;
    console.log('New WeChat:', newWechat);
    this.setData({
      'userInfo.wechat': newWechat
    });
  },
  
  confirmSex() {
    wx.cloud.database().collection('user').where({
      _openid: this.data.userInfo._openid 
    }).update({
      data: {
        sex: this.data.userInfo.sex
      },
      success: () => {
        console.log('性别更新成功');
        this.closeDialog();
        this.refreshPageContent();
      },
      fail: err => {
        console.error('性别更新失败', err);
      }
    });
  },
  
  confirmPhone() {
    wx.cloud.database().collection('user').where({
      _openid: this.data.userInfo._openid 
    }).update({
      data: {
        phone: this.data.userInfo.phone
      },
      success: () => {
        console.log('手机号更新成功');
        this.closeDialog();
        this.refreshPageContent();
      },
      fail: err => {
        console.error('手机号更新失败', err);
      }
    });
  },
  
  confirmWechat() {
    wx.cloud.database().collection('user').where({
      _openid: this.data.userInfo._openid 
    }).update({
      data: {
        wechat: this.data.userInfo.wechat
      },
      success: () => {
        console.log('微信号更新成功');
        this.closeDialog();
        this.refreshPageContent();
      },
      fail: err => {
        console.error('微信号更新失败', err);
      }
    });
  },
  
  
  
 
  
});
